<?php
class Usermodel extends CI_Model{
	function __construct(){
		parent::__construct();
	}
	
	//check user login
	function validate(){
		$this->db->where('username', $this->input->post('username'));
		$this->db->where('password',$this->input->post('password'));
		$query = $this->db->get('user');
		
		if ($query->num_rows == 1)
			return true;
		return false;
	}
	
	//get user by username
	function getUser($username){
		$sql = "SELECT * FROM user WHERE username = '$username'";
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0){
			foreach ($query->result() as $row){
				$data[] = $row;
			}
		}
		return $data;
	}
	
	//get profile of a student
	function getProfile($studentId){
		$this->db->select('*');
		$this->db->from('user');
		$this->db->join('list_students', 'student_id=user_id');
		$this->db->where('user_id',$studentId);
	//	$this->db->limit(1,0);
		$query = $this->db->get();
		if ($query->num_rows() > 0){
			foreach ($query->result() as $row){
				$data[] = $row;
			}
			return $data;
		}
		else 
			$data[] = false;
		return $data;
	}
	
	//list user by type: student - 1, teacher - 2, admin - 3.
	function listUser($type){
		$sql = "SELECT * FROM user WHERE type = '$type'";
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0){
			foreach ($query->result() as $row){
				$data[] = $row;
			}
			return $data;
		}
		else 
			$data[] = false;
		return $data;
	}
	
	//list all user
	function listAll(){
		$sql = "SELECT * FROM user";
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0){
			foreach ($query->result() as $row){
				$data[] = $row;
			}
			return $data;
		}
		else 
			$data[] = false;
		return $data;
	}
	
	//add new user
	function add($type){
		$fname = $this->input->post('fname');
		$lname = $this->input->post('lname');
		$user = $this->input->post('username');
		$pass = $this->input->post('password');
		$dOb = $this->input->post('dOb');
		$email = $this->input->post('email');
		$falculty = $this->input->post('falculty');
		if ($this->session->userdata('checkType') == 0){
			if (strcasecmp($this->input->post('type'), 'student') == 0)
				$type = 1;
			else if (strcasecmp($this->input->post('type'), 'teacher') == 0)
				$type = 2;
			else 
				$type = 3;	
		}
		$sql = "INSERT INTO user (username,password,firstname,lastname,dayOfBirth,email,falculty, type) 
		VALUES('$user','$pass','$fname','$lname','$dOb','$email','$falculty','$type')";
		$this->db->query($sql);
	}
	
	//delete user by id
	function delete($id){
		$sql = "DELETE FROM user WHERE user_id= $id";
		$this->db->query($sql);
	}
}